package com.blb.controller;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.blb.utils.UUIDUtils;

@Controller
@RequestMapping("common")
public class ResourceController {
	
	private static final String filePath = "D:/file_upload/";

	/**
	 * 上传文件
	 * @param files
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("upload")
	public String upload(@RequestParam("file")MultipartFile[] files) throws IllegalStateException, IOException{
		StringBuffer sb = new StringBuffer();
		for (int i =0; i<files.length; i++) {
			MultipartFile file = files[i];
			String filename = file.getOriginalFilename();
			String newFileName = UUIDUtils.getID() + filename.substring(filename.lastIndexOf("."));
			file.transferTo(new File(filePath + newFileName));
			
			sb.append(newFileName);
			if (i!=files.length-1) {
				sb.append(",");
			}
		}
		return "{\"name\" : \""+sb.toString()+"\"}";
	}
	
	/**
	 * 显示图片
	 * @param name
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("getImage")
	public ResponseEntity<byte[]> getImage(String name) throws IOException{
		File file = new File(filePath + name);
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.setContentType(MediaType.IMAGE_JPEG);
		if (!file.exists()) {
			return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(filePath + "1.jpg")), httpHeaders, HttpStatus.OK);
		}
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.OK);
	}
}
